package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.CommUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.widget.ListWheelAdapter;
import com.yxt.common.widget.OnWheelChangedListener;
import com.yxt.common.widget.WheelView;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Division;
import com.yxt.model.Valley;
import com.yxt.service.DivisionService;
import com.yxt.service.ValleyService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;  
import android.widget.ImageView;
import android.widget.TextView;

public class WaterOverStepActivity extends Activity {
	private static final int MENU_HE = Menu.FIRST+2;
	private static final int MENU_KU = Menu.FIRST + 3;
	private static final int MENU_CW = Menu.FIRST + 5;
	
	private Map<String,Map<String,String>> waters = new HashMap<String,Map<String,String>>();
	private String counttime = "";
	private DivisionService diviservice = new DivisionService(WaterOverStepActivity.this);
	private ValleyService vallservice = new ValleyService(WaterOverStepActivity.this);
	private TextView lblProvince;
	private TextView lblRiver;
	private List<Division> provinces;
	private List<Division> cities;
	private List<Division> county;
	private List<Valley> mainriver;
	private List<Valley> childriver;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.water_over);   //软件activity的布局	
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		
		lblProvince = (TextView)findViewById(R.id.lblProvince);
		lblRiver = (TextView)findViewById(R.id.lblRiver);
		lblProvince.setText(CommConstant.Main.CURRENT_AREA_NAME);
		lblRiver.setText(CommConstant.Main.CURRENT_RIVER_NAME);
		
		lblProvince.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				View view = View.inflate(WaterOverStepActivity.this, R.layout.comm_region, null);
				final AlertDialog menuDialog = new AlertDialog.Builder(WaterOverStepActivity.this).create();
				menuDialog.setView(view);
				menuDialog.show();
				final WheelView wheelProvince = (WheelView)view.findViewById(R.id.wheelProvince);
				final WheelView wheelCity = (WheelView)view.findViewById(R.id.wheelCity);
				final WheelView wheelCounty = (WheelView)view.findViewById(R.id.wheelCounty);
				String area = CommUtil.getDefaultAreaSql();			
				//获取区域列表
				provinces = diviservice.getDivisionByConditions(area);
				int currprovince = CommUtil.getCurrentRegionIndex(provinces, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_PROVINCE_TYPE);
				cities = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.CITY_TYPE+"' and parentCode='" + provinces.get(currprovince).getCode()+"'");
				int currcity = CommUtil.getCurrentRegionIndex(cities, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_CITY_TYPE);
				county = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.COUNTY_TYPE+"' and parentCode='" + cities.get(currcity).getCode()+"'");
				int currcounty = CommUtil.getCurrentRegionIndex(county, CommConstant.Main.CURRENT_AREA_CODE, CommConstant.Main.DEFAULT_COUNTY_TYPE);
				//设置当前项
				wheelProvince.setAdapter(new ListWheelAdapter<Division>(provinces,CommConstant.Config.REGION_MAXLENGTH));
				wheelCity.setAdapter(new ListWheelAdapter<Division>(cities,CommConstant.Config.REGION_MAXLENGTH));
				wheelCounty.setAdapter(new ListWheelAdapter<Division>(county,CommConstant.Config.REGION_MAXLENGTH));
				wheelProvince.setCurrentItem(currprovince);
				wheelCity.setCurrentItem(currcity);
				wheelCounty.setCurrentItem(currcounty);
				//添加事件
				wheelProvince.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						cities = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.CITY_TYPE+"' and parentCode = '"+provinces.get(wheelProvince.getCurrentItem()).getCode()+"'");
						wheelCity.setAdapter(new ListWheelAdapter<Division>(cities,CommConstant.Config.REGION_MAXLENGTH));
					}
				});
				wheelCity.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						county = diviservice.getDivisionByConditions("type = '"+CommConstant.Rain.COUNTY_TYPE+"' and parentCode = '"+cities.get(wheelCity.getCurrentItem()).getCode()+"'");	
						wheelCounty.setAdapter(new ListWheelAdapter<Division>(county,CommConstant.Config.REGION_MAXLENGTH));			
					}
				});
				
				Button btnConfirm = (Button)view.findViewById(R.id.btnConfirm);
				Button btnCancel = (Button)view.findViewById(R.id.btnCancel);
				btnConfirm.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						Division proDivision = provinces.get(wheelProvince.getCurrentItem());
						Division cityDivision = cities.get(wheelCity.getCurrentItem());
						Division countyDivision = county.get(wheelCounty.getCurrentItem());
						if (!CommConstant.Config.DEFAULT_NAME.equals(countyDivision.getName())) {
							CommConstant.Main.CURRENT_AREA_CODE = countyDivision.getCode();
							CommConstant.Main.CURRENT_AREA_NAME = countyDivision.getName();
							lblProvince.setText(countyDivision.getName());
						} else {
							if (!CommConstant.Config.DEFAULT_NAME.equals(cityDivision.getName())) {
								CommConstant.Main.CURRENT_AREA_CODE = cityDivision.getCode();
								CommConstant.Main.CURRENT_AREA_NAME = cityDivision.getName();
								lblProvince.setText(cityDivision.getName());
							} else {
								CommConstant.Main.CURRENT_AREA_CODE = proDivision.getCode();
								CommConstant.Main.CURRENT_AREA_NAME = proDivision.getName();
								lblProvince.setText(proDivision.getName());
							}
						}
						menuDialog.cancel();
						CommUtil.persistenceAreaInfo(getApplicationContext());
						initComponent();
					}			
				});
				btnCancel.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						menuDialog.cancel();
					}			
				});
			}			
		});
		
		lblRiver.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				View view = View.inflate(WaterOverStepActivity.this, R.layout.comm_river, null);
				final AlertDialog menuDialog = new AlertDialog.Builder(WaterOverStepActivity.this).create();
				menuDialog.setView(view);
				menuDialog.show();
				final WheelView wheelRiver = (WheelView)view.findViewById(R.id.wheelRiver);
				final WheelView wheelSubRiver = (WheelView)view.findViewById(R.id.wheelSubRiver);
				String mriver = CommUtil.getDefaultRiverSql(CommConstant.Water.DEFAULT_MAIN_RIVER);
				if (mriver.indexOf("type") == -1) {
					mriver += " and type = '"+CommConstant.Water.MAIN_TYPE+"'";
				}
				mainriver = vallservice.getValleyByCondtion(mriver);
				String sriver = CommUtil.getDefaultRiverSql(CommConstant.Water.DEFAULT_SUB_RIVER);
				int currmain = CommUtil.getCurrentRiverIndex(mainriver, CommConstant.Main.CURRENT_RIVER_CODE, CommConstant.Main.DEFAULT_MAIN_TYPE);
				if (sriver.indexOf("type") > -1) {//判断是否为空
					sriver += " and parentCode = '"+mainriver.get(currmain).getCode()+"'";
				} else {
					sriver += " and type = '"+CommConstant.Water.SUB_TYPE+"' and parentCode = '"+mainriver.get(currmain).getCode()+"'";
				}
				childriver = vallservice.getValleyByCondtion(sriver);
				int currsub = CommUtil.getCurrentRiverIndex(childriver, CommConstant.Main.CURRENT_RIVER_CODE, CommConstant.Main.DEFAULT_SUB_TYPE);
				wheelRiver.setAdapter(new ListWheelAdapter<Valley>(mainriver,CommConstant.Config.RIVER_MAXLENGTH));
				wheelSubRiver.setAdapter(new ListWheelAdapter<Valley>(childriver,CommConstant.Config.RIVER_MAXLENGTH));
				wheelRiver.setCurrentItem(currmain);
				wheelSubRiver.setCurrentItem(currsub);
				//添加事件
				wheelRiver.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						childriver = vallservice.getValleyByCondtion("type = '"+CommConstant.Water.SUB_TYPE+"' and parentCode = '"+mainriver.get(wheelRiver.getCurrentItem()).getCode()+"'");
						wheelSubRiver.setAdapter(new ListWheelAdapter<Valley>(childriver,CommConstant.Config.RIVER_MAXLENGTH));
					}
				});
				Button btnConfirm = (Button)view.findViewById(R.id.btnConfirm);
				Button btnCancel = (Button)view.findViewById(R.id.btnCancel);
				btnConfirm.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						Valley subValley = childriver.get(wheelSubRiver.getCurrentItem());
						Valley mainValley = mainriver.get(wheelRiver.getCurrentItem());
						if (!CommConstant.Config.DEFAULT_NAME.equals(subValley.getName())) {
							CommConstant.Main.CURRENT_RIVER_CODE = subValley.getCode();
							CommConstant.Main.CURRENT_RIVER_NAME = subValley.getName();
							lblRiver.setText(subValley.getName());
						} else {
							CommConstant.Main.CURRENT_RIVER_CODE = mainValley.getCode();
							CommConstant.Main.CURRENT_RIVER_NAME = mainValley.getName();
							lblRiver.setText(mainValley.getName());
						}
						CommUtil.persistenceRiverInfo(getApplicationContext());
						menuDialog.cancel();
						initComponent();
					}			
				});
				btnCancel.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						menuDialog.cancel();
					}			
				});
			}			
		});
		initComponent();
	}
	
	private void downloadWaterOver() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new WaterOverHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}		
	}

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		CommConstant.Sever.WATER_SERVER = server;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"waterover.xml");
		} else {
			URL url = new URL(server + "water/AlertCount.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class WaterOverHandler extends DefaultHandler {

		public void startDocument() throws SAXException {
			waters.clear();
		}
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("info".equals(localName)) {
				String type = attrs.getValue("type");
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				waters.put(type, data);
			} else if ("counttime".equals(localName)) {
				counttime = attrs.getValue("value");
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					ImageView image1 = (ImageView)findViewById(R.id.image1);
					ImageView image2 = (ImageView)findViewById(R.id.image2);
					ImageView image4 = (ImageView)findViewById(R.id.image4);

					TextView lblEndTime = (TextView)findViewById(R.id.lblEndTime);
					lblEndTime.setText(counttime);
					
					Map<String,String> data = waters.get(CommConstant.Water.HD_TYPE);
					TextView lbl1 = (TextView)findViewById(R.id.lbl1);
					lbl1.setText(data.get("name"));
					TextView lbl2 = (TextView)findViewById(R.id.lbl2);
					lbl2.setText(data.get("count") + " 个");
					if (!CommConstant.Rain.DEFAULT_FILTER.equals(data.get("count"))) {
						lbl2.setTextColor(Color.BLUE);
						lbl2.setOnClickListener(new TextItemOnClickListener(CommConstant.Water.HD_TYPE));
						image1.setOnClickListener(new ImageItemOnClickListener(CommConstant.Water.HD_TYPE));
					}
					
					data = waters.get(CommConstant.Water.SK_TYPE);
					TextView lbl3 = (TextView)findViewById(R.id.lbl3);
					lbl3.setText(data.get("name"));
					TextView lbl4 = (TextView)findViewById(R.id.lbl4);
					lbl4.setText(data.get("count") + " 个");
					if (!CommConstant.Rain.DEFAULT_FILTER.equals(data.get("count"))) {
						lbl4.setTextColor(Color.BLUE);
						lbl4.setOnClickListener(new TextItemOnClickListener(CommConstant.Water.SK_TYPE));
						image2.setOnClickListener(new ImageItemOnClickListener(CommConstant.Water.SK_TYPE));
					}
						
					
					data = waters.get(CommConstant.Water.CW_TYPE);
					TextView lbl7 = (TextView)findViewById(R.id.lbl7);
					lbl7.setText(data.get("name"));
					TextView lbl8 = (TextView)findViewById(R.id.lbl8);
					lbl8.setText(data.get("count") + " 个");
					if (!CommConstant.Rain.DEFAULT_FILTER.equals(data.get("count"))) {
						lbl8.setTextColor(Color.BLUE);
						lbl8.setOnClickListener(new TextItemOnClickListener(CommConstant.Water.CW_TYPE));
						image4.setOnClickListener(new ImageItemOnClickListener(CommConstant.Water.CW_TYPE));
					}
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadWaterOver();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();

	}

	private class ImageItemOnClickListener implements OnClickListener {
		private String type;
		
		public ImageItemOnClickListener(String type) {
			this.type = type;			
		}
		
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), WaterStationMapActivity.class);
			intent.putExtra("type", type);
			startActivity(intent);
		}
		
	}
	
	private class TextItemOnClickListener implements OnClickListener {
		private String type;
		
		public TextItemOnClickListener(String type) {
			this.type = type;			
		}
		
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), WaterStationListActivity.class);
			intent.putExtra("type", type);
			intent.putExtra("waterover", CommConstant.Water.WATER_OVER);
			startActivity(intent);
		}
		
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_HE, 1, R.string.menu_hedao);
		menu.add(0, MENU_KU, 2, R.string.menu_shuiku);
		menu.add(0, MENU_CW, 4, R.string.menu_chaowei);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case MENU_HE:
				intent.setClass(getApplicationContext(), WaterStationListActivity.class);
				intent.putExtra("type", CommConstant.Water.HD_TYPE);
				startActivity(intent);
				return true;
			case MENU_KU:
				intent.setClass(getApplicationContext(), WaterStationListActivity.class);
				intent.putExtra("type", CommConstant.Water.SK_TYPE);
				startActivity(intent);
				return true;
			case MENU_CW:	
				intent.setClass(getApplicationContext(), WaterStationListActivity.class);
				intent.putExtra("type", CommConstant.Water.CW_TYPE);
				startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
		diviservice.closeDB();
		vallservice.closeDB();
        ActivityStackControlUtil.remove(this);
	}
}